package com.pinhuba.bams.framework.http;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;


public class HttpClientHelper {

	public static DefaultHttpClient buildHttpClient(int connectionPoolTimeout,
			int connectionTimeout, int socketTimeout) {
		DefaultHttpClient client =new DefaultHttpClient();// HttpClientHelper.createHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(),connectionTimeout);
		HttpConnectionParams.setSoTimeout(client.getParams(), socketTimeout);
		return client;
	}

	private static DefaultHttpClient createHttpClient() {
		HttpParams params = new BasicHttpParams();
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		ClientConnectionManager mgr = new ThreadSafeClientConnManager(params,
				registry);
		
		return new DefaultHttpClient(mgr, params);
	}

	/**
	 * close httpClient
	 * 
	 * @param httpClient
	 */
	public static void closeClient(DefaultHttpClient httpClient) {
		if (httpClient != null && httpClient.getConnectionManager() != null) {
			httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
	}
}
